<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;

use app\admin\model\devmgmt\Device;
use app\admin\model\datamanagement\Thinfo;
use think\Log;


/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    private function print($msg)
    {
        LOG::write("[Dashboard] $msg", "info");
    }
    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        /*
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }
        */
        $totalDevice = Device::count();
        $onlineDevice = Device::where('state', '0')->count();
        $dbTableList = Db::query("SHOW TABLE STATUS");
        $devicelist = $this->get_device_list();
        $this->view->assign([
            'totaladmin'      => Admin::count(),
            'totalcategory'   => \app\common\model\Category::count(),
            'todayusersignup' => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'  => User::whereTime('logintime', 'today')->count(),
            'sevendau'        => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'       => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'        => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'        => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'     => count($dbTableList),
            'attachmentnums'  => Attachment::count(),
            'attachmentsize'  => Attachment::sum('filesize'),
            'picturenums'     => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'     => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
            'totaldevice'     => $totalDevice,
            'onlinecount'     => $onlineDevice,
            'onlinerate'      => sprintf("%.2f",($onlineDevice/$totalDevice)*100),
            'totaldata'       => Thinfo::count(),
            'lowRptTime'      => '2021-11-16 12:22:32',
            'devicelist'      => $devicelist,
        ]);

        //$this->assignconfig('column', array_keys($userlist));
        //$this->assignconfig('userdata', array_values($userlist));

        return $this->view->fetch();
    }

    private function get_device_list()
    {
        $devicelist = [];
        $list = Device::field('devicename')->select();

        foreach($list as $k => $v){
			$devicelist[]=$v['devicename'];
		}

        return $devicelist;
    }

    public function get_weekly_ehcart_info()
    {
        $devid = $this->request->get("devicename", '');
        $this->print("devicename=".$devid);
        $weeklytemp_hi = [];
        $weeklytemp_low = [];
        $starttime = date("Y-m-d H:m:s",Date::unixtime('day', -7));
        $endtime = date("Y-m-d H:m:s",Date::unixtime('day', 0, 'end'));
        $this->print("start:".$starttime.",endtime:".$endtime);

        $weeklylist = Db("datamanagement_thinfo")
        ->where('timeStamp', 'between time', [$starttime, $endtime])
        ->where('devId' , '=', $devid)
        ->field('MAX(temp) as max_temp, MIN(temp) as min_temp,  DATE_FORMAT(timeStamp, "%y-%m-%d") AS report_date')
        ->group('report_date')
        ->limit(7)
        ->select();

        foreach ($weeklylist as $k => $v) {
            $weeklytemp_hi[$v['report_date']] = $v['max_temp'];
            $weeklytemp_low[$v['report_date']] = $v['min_temp'];
        }
        //$this->print(json($weeklytemp_hi));
        $result = array("column"=> array_keys($weeklytemp_hi),"weeklyhigh" => array_values($weeklytemp_hi),"weeklylow" => array_values($weeklytemp_low));

        return $result;
    }

}
